const allServices = require('../../controller/mysql');
const { getKey } = require('../../util/getKey')
const { timeHanle, timeMD } = require('../../util/oderNo')
const jwt = require('jsonwebtoken')
const secret = 'mysecretkey';
const Backend = {
    userList: async (req, res) => {
        const { page, pageSize } = req.body;
        const offset = (page - 1) * pageSize;
        const limit = Number(pageSize);
        const sql = "SELECT * FROM admin_user LIMIT ? OFFSET ?";
        const sql1 = "SELECT COUNT(*) AS count FROM admin_user";
        const data = await queryWithPaging(sql, sql1, limit, offset)
        console.log(data);
        res.send({
            code: 200,
            mgs: 'success',
            res: data.row,
            count: data.count
        })
    },
    allOrder: async (req, res) => {
        const { page, pageSize } = req.body;
        const offset = (page - 1) * pageSize;
        const limit = Number(pageSize);
        const sql = "SELECT * FROM order_list LIMIT ? OFFSET ?";
        const sql1 = "SELECT COUNT(*) AS count FROM order_list";
        const data = await queryWithPaging(sql, sql1, limit, offset)
        res.send({
            code: 200,
            mgs: 'success',
            res: data.row,
            count: data.count
        })
    },
    getToken: (req, res) => {
        res.send(getKey())
    },
    uploadShop: (req, res) => {
        const params = [req.body.shop_name, req.body.shop_price, req.body.shop_dec, req.body.shop_img, req.body.tag]
        const sql = `insert into shoplist (shop_name, shop_price, shop_dec, shop_img, tag) values
        (?,?,?,?,?)`
        allServices.query(sql, params).then(result => {
            if (result.affectedRows) {
                res.send({
                    code: 200,
                    msg: 'success'
                })
            }
        })
    },
    editShop: (req, res) => {
        const params = [req.body.shop_name, req.body.shop_price, req.body.tag, req.body.shop_img, req.body.shop_dec, req.body.shop_id]
        const sql = `update shoplist  set shop_name=?,shop_price=?,
    tag=?,shop_img=?,shop_dec=? where shop_id =?`
        allServices.query(sql, params).then(result => {
            res.send({
                code: 200,
                msg: 'success'
            })
        })
    },
    shopDelete: (req, res) => {
        const sql = `DELETE FROM shoplist WHERE shop_id = ?`;
        allServices.query(sql, [req.query.shop_id]).then(result => {
            res.send({
                code: 200,
                msg: 'success'
            });
        })
    },
    orderRefund: (req, res) => {
        const sql = `DELETE FROM order_list WHERE order_id = ?`;
        allServices.query(sql, [req.query.order_id]).then(result => {
            res.send({
                code: 200,
                msg: 'success'
            });
        })
    },
    login: (req, res) => {
        const sql = 'select username, password,id,role from admin_user where username=?'
        const { username, password, role } = req.body
        allServices.query(sql, [username]).then(result => {
            if (result.length) {
                if (result[0].username == username && result[0].password == password && result[0].role == role) {
                    const payload = { user_id: result[0].id };
                    const options = { expiresIn: '1h' };
                    const token = jwt.sign(payload, secret, options);
                    console.log(result);
                    res.send({
                        code: 200,
                        msg: 'success',
                        token: token,
                        role:result[0].role
                    })
                }
                else {
                    res.status(404).send({
                        code: 404,
                        msg: '用户选择、账号或密码错误'
                    })
                }
            }
        }).catch(err => {
            console.log(err);
            throw err
        })
    },
    register: (req, res) => {
        const { username, password, tel, role } = req.body
        const sql = `select * from admin_user where username=?`
        const sql1 = 'insert into admin_user (username, password, tel, role) values (?,?,?,?)'
        allServices.query(sql, [username]).then(result => {
            if (result.length) {
                res.send({
                    code: 404,
                    msg: '账号名重复'
                })
            }
            else {
                allServices.query(sql1, [username, password, tel, role]).then(result => {
                    res.send({
                        code: 200,
                        msg: '注册成功'
                    })
                })
            }
        })
    },
    userUpdate:(req, res) => {
        const {username, password, tel, role, id} = req.body
        const sql = `update admin_user set username=?,password=?,tel=?,role=? where id=?`
        allServices.query(sql, [username, password, tel, role, id]).then(result => {
            if(result.affectedRows) {
                res.send({
                    code:200,
                    msg:'success',
                })
            }
            else {
                res.status(404).send({
                    code:404,
                    msg:'信息不全'
                })
            }
        })
    },
    userDelete:(req, res) => {
        const sql = 'delete from admin_user where id=?'
        allServices.query(sql, [req.query.id]).then(result => {
            if(result.affectedRows) {
                res.send({
                    code:200,
                    msg:'success'
                })
            }
        })
    },
    orederData: (req, res) => {
        const sql = `SELECT tag as name, COUNT(*) AS value FROM order_list GROUP BY tag;`;
        allServices.query(sql).then(result => {
            res.send({
                code: 200,
                msg: 'success',
                res: result
            })
        })
    },
    dayOrder: (req, res) => {
        const sql = `SELECT Date(create_time) as time, COUNT(*) AS value FROM order_list GROUP BY Date(create_time);`
        allServices.query(sql).then(result => {
            const time = []
            const value = []
            result.forEach(item => {
                time.push(timeMD(item.time))
            })
            result.forEach(item => {
                value.push(item.value)
            })
            res.send({
                code: 200,
                msg: 'success',
                time: time,
                value: value
            })
        })
    },
    log: async (req ,res) => {
        const { page, pageSize } = req.body;
        const offset = (page - 1) * pageSize;
        const limit = Number(pageSize);
        const sql = "SELECT * FROM log LIMIT ? OFFSET ?";
        const sql1 = "SELECT COUNT(*) AS count FROM log";
        const data = await queryWithPaging(sql, sql1, limit, offset)
        data.row.forEach(item => {
            item.login_time = timeHanle(item.login_time)
        })
        res.send({
            code: 200,
            mgs: 'success',
            res: data.row,
            count: data.count
        })
    },
    searchGoods: async (req, res) => {
        const { page, pageSize, searchVal } = req.body;
        const offset = (page - 1) * pageSize;
        const limit = Number(pageSize);
        const sql = 'select shop_name,tag,shop_dec,shop_id,shop_img,shop_price from shoplist where shop_name like ? or shop_dec like ? or tag like ? group by shop_id LIMIT ? OFFSET ? '
        const sql1 = 'select Count(*) as count from shoplist where shop_name like ? or shop_dec like ? or tag like ?'
        const [{count}] = await allServices.query(sql1, [`%${searchVal}%`, `%${searchVal}%`, `%${searchVal}%`])
        allServices.query(sql, [`%${searchVal}%`, `%${searchVal}%`, `%${searchVal}%`, limit, offset]).then(result => {
            console.log(result.length);
            res.send({
                code:200,
                msg:'success',
                res:result,
                count:count
            })
        }) 
    }
}

async function queryWithPaging(sql, countSql, limit, offset) {

    const [row, [{count}]] = await Promise.all([allServices.query(sql, [limit, offset]), allServices.query(countSql)])
    row.forEach(item => {
        item.create_time = timeHanle(item.create_time)
    })
    return { row, count }
}

module.exports = Backend